<template>
  <div id="app">
    <router-view></router-view>
  </div>
</template>

<script>
import wx from 'weixin-js-sdk'
import { mineApi } from '@/api'
import AppUtils from '@/utils/AppUtils'
import { mapGetters, mapActions } from 'vuex'
export default {
  name: 'app',
  computed: {
    ...mapGetters([
      'user',
      'token'
    ])
  },
  created() {
    // if (!this.token) {
    //   this.$router.push('/login')
    // }
  },
  async mounted() {
  },
  methods: {
    ...mapActions([
      'LoginByApp'
    ])
  },
  watch: {
    $route: {
      async handler(to, from) {
        if (from && (from.path === '/login') && !this.userToken && !to.meta.lessLogin) {
          console.log('this.userToken', this.userToken)
          console.log('to.meta.lessLogin', to.meta.lessLogin)
          console.log('未登录')
          this.$router.push('/home')
        }
        let token = to.query.token
        if (!token && to.query.id && !this.token) {
          token = to.query.id.split('token=')[1]
        }
        if (token) {
          this.LoginByApp({ token: token })
          return
        }
        if (to.name && AppUtils.isWechat() && !this.token) {
          const res = await mineApi.loginByWechat({
            // returnUrl: location.href.split('#')[0]
            returnUrl: encodeURIComponent(location.origin + location.pathname + '#' + to.fullPath)
          })
          console.log('res', res)
          location.href = res
          return
          // location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx595ec526353b2715&redirect_uri=http://www.hailangfc.com/api/authorize?returnUrl=www.hailangfc.com&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect'
        }
        if (AppUtils.isWechat()) {
          const sdk = await mineApi.getWechatSdk({
            strUrl: location.href.split('#')[0]
          })
          AppUtils.setWeChat(wx, {
            app_id: 'wx595ec526353b2715',
            nonce_str: sdk.data.noncestr,
            signature: sdk.data.signature,
            timestamp: sdk.data.timestamp
          }, this.user)
          console.log('sdk', sdk)
        }
      },
      immediate: true,
      deep: true
    }
  }
}
</script>
